package com.weishuang.monitor.leader.config.client;

import com.weishuang.monitor.leader.commons.enums.ICODE;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Slf4j
@Component
public class ClientAuthenticationProvider implements AuthenticationProvider {

    /**
     * 用户信息服务
     */
    @Autowired
    private ClientUserDetailsService userDetailsService;

    /**
     * 校验账户密码
     * @param userDetails
     * @param authentication
     * @throws AuthenticationException
     */
    protected void additionalAuthenticationChecks(UserDetails userDetails,
                                                  ClientAuthenticationToken authentication)
            throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            log.debug("验证失败:没有提供凭据");
            throw new BadCredentialsException(ICODE.LOGIN_USER_IS_NULL.getMsg());
        }
        String presentedPassword = authentication.getCredentials().toString();
        if (!presentedPassword.equals(userDetails.getPassword())) {
            log.debug("验证失败:密码与存储值不匹配");
            throw new BadCredentialsException(ICODE.LOGIN_USER_IS_NULL.getMsg());
        }
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.isInstanceOf(ClientAuthenticationToken.class, authentication,() -> "只支持ClientAuthenticationToken");
        String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();
        UserDetails user;
        try {
            user = retrieveUser(username);
        }catch (UsernameNotFoundException notFound) {
            log.debug("User '" + username + "' not found");
            throw new BadCredentialsException(ICODE.LOGIN_USER_IS_NULL.getMsg());
        }
        try {
            additionalAuthenticationChecks(user,(ClientAuthenticationToken) authentication);
        }catch (AuthenticationException exception) {
            throw exception;
        }
        Object principalToReturn = user;
        return createSuccessAuthentication(principalToReturn, authentication, user);
    }

    /**
     * 创建登录成功用户证明
     * @param principal
     * @param authentication
     * @param user
     * @return
     */
    protected Authentication createSuccessAuthentication(Object principal,
                                                         Authentication authentication, UserDetails user) {
        ClientAuthenticationToken result = new ClientAuthenticationToken(principal, authentication.getCredentials(), user.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return ClientAuthenticationToken.class.isAssignableFrom(authentication);
    }


    /**
     * 根据用户名获取用户信息，用于校验
     * @param username
     * @return	返回用户信息
     * @throws AuthenticationException
     */
    protected UserDetails retrieveUser(String username)
            throws AuthenticationException {
        try {
            UserDetails loadedUser = userDetailsService.loadUserByUsername(username);
            if (loadedUser == null) {
                throw new InternalAuthenticationServiceException(ICODE.LOGIN_USER_IS_NULL.getMsg());
            }
            return loadedUser;
        }catch (UsernameNotFoundException ex) {
            throw ex;
        }catch (InternalAuthenticationServiceException ex) {
            throw ex;
        }catch (Exception ex) {
            throw new InternalAuthenticationServiceException(ex.getMessage(), ex);
        }
    }
}
